package edu.taru.office.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import edu.taru.office.common.Constants;
import edu.taru.office.common.JsonResult;
import edu.taru.office.util.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * 通用Controller 例如验证码
 *
 */
@Controller
public class CommonController  {
    private Logger logger= LoggerFactory.getLogger(CommonController.class);

    @Value("${web.upload.image-path}")
    String webUploadImagePath;




    @Autowired
    DefaultKaptcha defaultKaptcha;


    /**
     * 进入页面
     * @param page
     * @return
     */
    @RequestMapping("/view/{page}")
    public  String   forward(@PathVariable("page") String page){
        return  page;
    }

    @RequestMapping("/view/{parent}/{page}")
    public  String  forward(@PathVariable("parent") String parent ,@PathVariable("page") String page){
        return   parent+"/"+page;
    }

    @RequestMapping("/common/kaptcha")
    public void  createKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute(Constants.VERIFY_CODE_KEY, createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
            logger.info("验证码: {} ",httpServletRequest.getSession().getAttribute(Constants.VERIFY_CODE_KEY));
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    /**
     * 上传文章头像
     * @param
     * @return
     */

    @RequestMapping("/common/upload")
    @ResponseBody
    public  Object   upload(@RequestParam("file_data") MultipartFile multipartFile){
        JsonResult<String>  jsonResult=null;
        System.out.println(multipartFile.getSize()+"***********************");
        System.out.println("*************************");
        if(!multipartFile.isEmpty()){

            try {
                String  imageName= ImageUtil.save(multipartFile,webUploadImagePath);
                jsonResult=new JsonResult<String>(Constants.STATUS_OK,"上传成功",imageName);
            } catch (Exception e) {
                e.printStackTrace();
                jsonResult=new JsonResult<String>(Constants.STATUS_ERROR,"上传异常");
            }

        }else{
            jsonResult=new JsonResult<String>(Constants.STATUS_NO_DATA,"没有上传数据");
        }

        return jsonResult;
    }




}
